package dao;

import java.io.Serializable;
import java.util.List;

import tables.RestTable;

import com.epam.grsulab.webapi.dao.AbstractDao;
import entity.Travel;

public class TravelDao extends AbstractDao<RestTable, Travel> {

	public TravelDao(final String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(final Travel newTravel) {
		// set ID
		newTravel.setId(getNextId());
		// get existing data
		final RestTable table = deserializeFromXml();
		// add new row
		table.getRows().add(newTravel);
		// save data
		serializeToXml(table);
	}

	@Override
	public void update(final Travel travel) {
		// get existing data
		final RestTable table = deserializeFromXml();
		// find by ID
	
		for (final Travel row : table.getRows()) {
			if (row.getId().equals(travel.getId())) {
				// found!!!
				// copy data
				row.setPrice(travel.getPrice());
				row.setType(travel.getType());
				break;
			}
		}
		// save updated table
		serializeToXml(table);
	}

	@Override
	public Travel get(final Serializable id) {
		// get existing data
		final RestTable table = deserializeFromXml();
		// find by ID
		for (final Travel row : table.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}

	@Override
	public List<Travel> getAll() {
		// get existing data
		final RestTable flightTable = deserializeFromXml();
		return flightTable.getRows();
	}

	@Override
	public void delete(final Serializable id) {
		// get existing data
		final RestTable table = deserializeFromXml();
		// find by ID
		Travel toBeDeleted = null;
		for (final Travel row : table.getRows()) {
			if (row.getId().equals(id)) {
				// found!!!
				toBeDeleted = row;
				break;
			}
		}
		// remove from list
		table.getRows().remove(toBeDeleted);
		// save updated table
		serializeToXml(table);
	}

	@Override
	protected Class<RestTable> getTableClass() {
		return RestTable.class;
	}
}
